<?php

/**
 *    退款维权管理控制器
 *
 *    @author    Garbin
 *    @usage    none
 */
class RefundApp extends MemberbaseApp
{
	var $_order_mod;
	var $_order_log_mod;
	var $_order_extm_mod;
	var $_goods_mod;
	var $_ordergoods_mod;
	var $_refund_mod;
	var $_store_mod;
	var $_member_mod;
	var $_refund_message_mod;
	
	function __construct()
    {
        $this->RefundApp();
    }
    function RefundApp()
    {
        parent::__construct();
        $this->_order_mod = &m('order');

		$this->_order_extm_mod = &m('orderextm');
        $this->_goods_mod = &m('goods');
		$this->_ordergoods_mod = &m('ordergoods');
		$this->_refund_mod = &m('refund');
		$this->_store_mod = &m('store');
		$this->_member_mod = &m('member');
		$this->_refund_message_mod = &m('refund_message');
    }
	
    function index()
    {	
		$_GET['status'] == 'on' && $condition = " AND status NOT IN ('SUCCESS','CLOSED') ";
		$page   =   $this->_get_page(10);   //获取分页信息
		$refunds = $this->_refund_mod->find(array(
			'conditions'=>'buyer_id='.$this->visitor->get('user_id').$condition,
			'limit'=>$page['limit'],
			'order'     => 'created desc',
			'count'   => true
		));
		$page['item_count']=$this->_refund_mod->getCount();
		foreach($refunds as $key=>$refund)
		{
			$store = $this->_store_mod->get(array('conditions'=>'store_id='.$refund['seller_id'],'fields'=>'store_name,owner_name'));
			$refunds[$key]['store_name']=$store['store_name'];
			$refunds[$key]['user_name'] = $store['owner_name'];
			$ordergoods = $this->_ordergoods_mod->find(array('conditions'=>'order_id='.$refund['order_id'],'fields'=>'goods_name'));
			if(count($ordergoods) > 1){
				$ext = Lang::get('and_more');
			} else $ext = '';
			$goods = current($ordergoods);
			
			$refunds[$key]['goods_name'] = $goods['goods_name'] . $ext;
			
			$order = $this->_order_mod->get(array('conditions'=>'order_id='.$refund['order_id'],'fields'=>'order_sn'));
			$refunds[$key]['order_sn'] = $order['order_sn'];
			$refunds[$key]['refund_fee'] = $refund['refund_goods_fee'] + $refund['refund_shipping_fee'];
		}
		$this->_format_page($page);
		$this->assign('page_info', $page); 
		
		
	
		$this->_get_curlocal_title('refund_apply');
        $this->_config_seo('title', Lang::get('member_center'));
		
		$this->assign('refunds',$refunds);
		$this->display('refund.index.html');
		
	}
	function view()
	{
		$refund_id = empty($_GET['refund_id'])? 0 : intval($_GET['refund_id']);
		if(!$refund_id){
			return;
		}
		
		/* 同时验证该退款是否可以查看 */
		$refund = $this->_refund_mod->get(array('conditions'=>'refund_id='.$refund_id.' and (buyer_id='.$this->visitor->get('user_id').' or seller_id='.$this->visitor->get('user_id').')'));
		if(!$refund){
			$this->show_warning('refund_not_exist');
			return;
		}
		if(!IS_POST)
		{
			$refund['shipped_text'] = Lang::get('shipped_'.$refund['shipped']);
			$refund['refund_fee'] = $refund['refund_goods_fee'] + $refund['refund_shipping_fee'];
			
		
			$this->_get_curlocal_title('refund_view');
        	$this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('refund_view'));
			
			$page   =   $this->_get_page(5);   //获取分页信息
			$refund['message'] = $this->_refund_message_mod->find(array(
				'conditions'=>'refund_id='.$refund_id,
				'order'=>'created desc',
				'limit'=>$page['limit'],
				'count'   => true				
			));	
			$page['item_count']=$this->_refund_message_mod->getCount();
			$this->_format_page($page);
			$this->assign('page_info', $page); 
			$this->assign('refund',$refund);
			$this->display('refund.view.html');			
		}
		//  新增退款留言
		else
		{
			/* 关闭或者是成功的退款，不能添加留言 */
			if($refund['status']=='SUCCESS' || $refund['CLOSED']){
				$this->show_warning('add_refund_message_not_allow');
				return;
			}
			
			$refund_image = $this->_upload_files();
            if ($refund_image === false){
				$this->show_warning('refund_message_image_upload_error');
                return;
            }
			$data = array(
				'owner_id'	=> $this->visitor->get('user_id'),
				'owner_role'=> $refund['buyer_id']==$this->visitor->get('user_id') ? 'buyer' : ($refund['seller_id']==$this->visitor->get('user_id') ? 'seller' : 'admin'),
				'refund_id'	=> $refund_id,
				'content'	=> htmlspecialchars(trim($_POST['content'])),
				'pic_url'	=> $refund_image['refund_cert'],
				'created'	=> gmtime()				
			);
			$this->_refund_message_mod->add($data);
			$this->show_message('add_ok');
		}
	}
	/* 申请退款 */
	function add()
	{
		$order_id = intval($_GET['order_id']);
		
		/* 如果已存在退款记录，则直接访问 */
		if($refund = $this->_refund_mod->get('order_id='.$order_id)) {
			header('Location:index.php?app=refund&act=edit&refund_id='.$refund['refund_id']);
			exit;
		}

		/* 验证该订单是否可以申请退款 */
		$this->_available_refund($order_id);

		$order = $this->_order_mod->get($order_id);

		$shipping_info = $this->_order_extm_mod->get($order_id);


		if(!IS_POST)
		{
			$refund = array();
			
			$refund['goods_fee'] = $order['order_amount'] - $shipping_info['shipping_fee'];
			
			$refund['total_fee'] =  $order['order_amount'];
			
			$refund['shipping_fee'] = $shipping_info['shipping_fee'];

			$this->assign('refund', $refund);
			
			$this->_get_curlocal_title('refund_add');
        	$this->_config_seo('title', Lang::get('member_center'));
			$this->display('refund.form.html');
			
		}
		else 
		{
			// 检查提交的数据
			
			$this->_check_post_data($order_id, $_POST);

			$refund_goods_fee    = $_POST['refund_goods_fee'] ? $_POST['refund_goods_fee'] : 0;
			$refund_shipping_fee = $_POST['refund_shipping_fee'] ? $_POST['refund_shipping_fee'] : 0;

			$data =  array(
				'refund_sn'				=>$this->_refund_mod->gen_refund_sn(),
				'order_id' 				=>$order_id,
				'refund_reason'			=>htmlspecialchars(trim($_POST['refund_reason'])),
				'refund_desc'   		=>htmlspecialchars(trim($_POST['refund_desc'])),
				'total_fee'				=>$order['order_amount'],
				'goods_fee'	    		=>$order['order_amount'] - $shipping_info['shipping_fee'], // 考虑折扣情况，所以不能直接等于 $order['goods_amount']
				'shipping_fee'			=>$shipping_info['shipping_fee'],
				'refund_goods_fee'		=>$refund_goods_fee,
				'refund_shipping_fee'	=>$refund_shipping_fee,
				'shipped'				=>$_POST['shipped'] ? intval(trim($_POST['shipped'])) : 0,
				'buyer_id'				=>$order['buyer_id'],
				'seller_id'				=>$order['seller_id'],
				'status'				=>'WAIT_SELLER_AGREE', // 买家已经申请退款，等待卖家同意
				'created'				=>gmtime(),
			);
			if($refund_id = $this->_refund_mod->add($data)) {
				
				$this->_refund_message_mod->add(array(
					'owner_id'	=> $this->visitor->get('user_id'),
					'owner_role'=> 'buyer',
					'refund_id'	=> $refund_id,
					'content'	=> sprintf(LANG::get('apply_refund_content_change'), $_POST['refund_goods_fee'], $refund_shipping_fee, LANG::get('shipped_'.$_POST['shipped']), $_POST['refund_reason'], $_POST['refund_desc']),
					'created'	=> gmtime(),
				));
				
				$this->show_message('add_ok','back_list', url('app=refund'));
			}
		}
	}
	function edit()
	{
		$refund_id = empty($_GET['refund_id'])? 0 : intval($_GET['refund_id']);
		if(!$refund_id){
			$this->show_warning('no_such_refund');
			return;
		}
		
		/* 验证当前用户对该退款是否有编辑的权限 */
		$refund = $this->_refund_mod->get(array('conditions'=>'(status != "SUCCESS" AND status != "CLOSED" AND status != "WAIT_ADMIN_AGREE") and refund_id='.$refund_id.' and buyer_id='.$this->visitor->get('user_id')));
		if(!$refund){
			$this->show_warning('refund_not_allow_edit');
			return;
		}
		
		if(!IS_POST)
		{
			$this->assign('refund', $refund);
			
			$this->_get_curlocal_title('refund_edit');
        	$this->_config_seo('title', Lang::get('member_center'));
			$this->display('refund.form.html');			
		}
		else
		{	
			// 检查提交的数据

			$this->_check_post_data($refund['order_id'], $_POST);

			$data =  array(
				'status'				=> 'WAIT_SELLER_CONFIRM',// 退款申请等待卖家确认中(买家修改后)
				'refund_reason'			=> htmlspecialchars(trim($_POST['refund_reason'])),
				'refund_desc'   		=> htmlspecialchars(trim($_POST['refund_desc'])),
				'refund_goods_fee'		=> trim($_POST['refund_goods_fee']),
				'refund_shipping_fee'	=> trim($_POST['refund_shipping_fee']),
				'shipped'				=> $_POST['shipped'] ? intval(trim($_POST['shipped'])) : 0,
			);
			$this->_refund_mod->edit($refund_id,$data);
			
			$this->_refund_message_mod->add(array(
				'owner_id'	=> $this->visitor->get('user_id'),
				'owner_role'=> 'buyer',
				'refund_id'	=> $refund_id,
				'content'	=> sprintf(LANG::get('refund_content_change'), $_POST['refund_goods_fee'], $_POST['refund_shipping_fee'], LANG::get('shipped_'.$_POST['shipped']), $_POST['refund_reason'], $_POST['refund_desc']),
				'created'	=> gmtime(),
			));
					
			$this->show_message('edit_ok','back_list', url('app=refund'));
		}
	}
	/* 要求客服介入处理 */
	function ask_customer()
	{
		$refund_id = empty($_GET['refund_id'])? 0 : intval($_GET['refund_id']);
		if(!$refund_id){
			$this->json_error('handle_fail');
			return;
		}
		/* 验证当前用户是否有对该退款有要求客服介入的权限*/
		$refund = $this->_refund_mod->get(array('conditions'=>'ask_customer !=1 and (status!="SUCCESS" AND status!="CLOSED") and refund_id='.$refund_id.' and (buyer_id='.$this->visitor->get('user_id').' or seller_id='.$this->visitor->get('user_id').')','fields'=>'refund_id,refund_sn,buyer_id,seller_id'));
		if(!$refund){
			$this->json_error('ask_customer_not_allow');
			return;
		}
		$this->_refund_mod->edit($refund_id,array('ask_customer'=>1));
		
		/* 同时插入退款处理日志 */
		if($refund['buyer_id']==$this->visitor->get('user_id')){
			$owner_role = 'buyer';
		} else {
			$owner_role = 'seller';
		}
		$data = array(
			'owner_id'	=> $this->visitor->get('user_id'),
			'owner_role'=> $owner_role,
			'refund_id'	=> $refund_id,
			'content'	=> sprintf(Lang::get('ask_customer_content_change'), Lang::get($owner_role)),
			'created'	=> gmtime(),		
		);
		if(!$this->_refund_message_mod->add($data)) {
			$this->json_error('handle_fail');
			return;
		}
		
		$this->json_result('', 'ask_customer_ok');
	}
	/* 卖家同意退款 */
	function agree()
	{
		$refund_id = empty($_GET['refund_id']) ? 0 : intval($_GET['refund_id']);
		if(!$refund_id){
			$this->json_error('handle_fail');
			return;
		}
		
		/* 验证当前用户对该退款是否有同意权限 */
		$refund = $this->_refund_mod->get(array('conditions'=>'(status !="SUCCESS" AND status !="CLOSED" AND status !="WAIT_ADMIN_AGREE") and refund_id='.$refund_id.' and seller_id='.$this->visitor->get('user_id')));
		
		if(!$refund){
			$this->json_error('agree_no_allow');
			return;
		}
		
		$order_id 		= $refund['order_id'];
		
		$order_info		= $this->_order_mod->get($order_id);
		$seller_info  	= $this->_member_mod->get($order_info['seller_id']);
		$buyer_info   	= $this->_member_mod->get($order_info['buyer_id']);
		
		/* 退款后的积分处理（积分返还，积分赠送） */
		Psmb_init()->_handle_order_integral_return($order_info, $refund);
		
		/* 如果订单是通过预存款等虚拟货币支付（不同的支付形式，采取不同的处理，目前只处理预存款支付方式的退款） */
		if($order_info['payment_code'] == 'deposit')
		{
			/* 转到对应的业务实例，不同的业务实例用不同的文件处理，如购物，卖出商品，充值，提现等，每个业务实例又继承支出或者收入 */
			$depopay_type    =&  dpt('outlay', 'refund');
			$result 		= $depopay_type->submit(array(
				'trade_info' =>  array('user_id'=>$order_info['seller_id'],'party_id'=>$order_info['buyer_id'],'amount'=>$refund['refund_goods_fee'] + $refund['refund_shipping_fee']),
				'extra_info' =>  $order_info + array('refund_id'=> $refund_id, 'seller_user_name'=>$seller_info['user_name'],'operator' => 'seller'),
				'post'		 =>	 $_POST,
			));
			if(!$result)
			{
				$this->json_error($depopay_type->_get_errors());
				return;
			}
			
			$this->json_result('', 'seller_agree_refund_ok');
		}
		/* 通过非虚拟货币支付的订单，不考虑退款问题 */
		else{
			
			$this->json_error('payment_not_support_refund');
			return;
		}
	}
	
	/* 拒绝退款 */
	function refuse()
	{
		$refund_id = empty($_GET['refund_id'])? 0 : intval($_GET['refund_id']);
		if(!$refund_id){
			$this->show_warning('refuse_not_allow');
			return;
		}
		
		/* 验证当前用户对该退款是否有拒绝权限 */
		$refund = $this->_refund_mod->get(array('conditions'=>'(status!="SUCCESS" AND status!="CLOSED" AND status!="WAIT_ADMIN_AGREE") and refund_id='.$refund_id.' and seller_id='.$this->visitor->get('user_id')));
		
		if(!$refund){
			$this->show_warning('refuse_not_allow');
			return;
		}
		
		if(!IS_POST)
		{
			$refund['refund_fee'] = $refund['refund_goods_fee'] + $refund['refund_shipping_fee'];
			$this->assign('refund', $refund);
			
			$this->_get_curlocal_title('refund_refuse');
        	$this->_config_seo('title', Lang::get('member_center'));
			$this->display('refund.refuse.html');			
		}
		else
		{
			$refund_image = $this->_upload_files();
            if ($refund_image === false)
            {
				$this->show_warning('refund_message_image_upload_error');
                return;
            }
			
			$this->_refund_mod->edit($refund_id,array('status'=>'SELLER_REFUSE_BUYER'));
			
			$data = array(
				'owner_id'	=> $this->visitor->get('user_id'),
				'owner_role'=> 'seller',
				'refund_id'	=> $refund_id,
				'content'	=> sprintf(Lang::get('refuse_content_change'),htmlspecialchars(trim($_POST['content']))),
				'pic_url'	=> $refund_image['refund_cert'],
				'created'	=> gmtime()				
			);
			$this->_refund_message_mod->add($data);
			$this->show_message('submit_ok','back_list', url('app=refund&act=view&refund_id='.$refund_id));	
		}
		
	}
	/* 取消退款 */
	function cancel()
	{
		$refund_id = empty($_GET['refund_id']) ? 0 : intval($_GET['refund_id']);
		if(!$refund_id){
			$this->json_error('handle_fail');
			return;
		}
		/* 验证是否具有取消该退款的权限 */
		$refund = $this->_refund_mod->get(array('conditions'=>'(status!="SUCCESS" AND status!="CLOSED" AND status!="WAIT_ADMIN_AGREE") and refund_id='.$refund_id.' and buyer_id='.$this->visitor->get('user_id'),'fields'=>'refund_id,refund_sn'));
		if(!$refund)
		{
			$this->json_error('cancel_not_allow');
			return;
		}
		$this->_refund_mod->edit($refund_id, array('status'=>'CLOSED', 'end_time' => gmtime()));
		
		$data = array(
			'owner_id'	=> $this->visitor->get('user_id'),
			'owner_role'=> 'buyer',
			'refund_id'	=> $refund_id,
			'content'	=> sprintf(Lang::get('cancel_content_change'), $refund['refund_sn']),
			'created'	=> gmtime(),
		);
		if(!$this->_refund_message_mod->add($data)) {
			$this->json_error('handle_fail');
			return;
		}
		$this->json_result('', 'cancel_ok');
	}

	function _available_refund($order_id)
	{
		if(!$order_id) {
			$this->show_warning('Hacking Attempt');
			exit;

		}
		
		/* 验证是否已经添加过退款申请 */
		if($this->_refund_mod->get(array('conditions'=>'order_id='.$order_id,'fields'=>'refund_id'))){

			$this->show_warning('该订单已经申请过退款申请，不能重复申请。');
			exit;

		}
		
		/* 验证当前订单是否是当前用户的 */

		$order = $this->_order_mod->get(array('conditions'=>'order_id='.$order_id.' and buyer_id='.$this->visitor->get('user_id'),'fields'=>'order_id,status,payment_code'));

		if(empty($order)){
			$this->show_warning('您要退款款的订单不存在');
			exit;

		} 
		/* 如果订单状态是已完成的,或者是已取消的等不能申请退款，只有订单状态是已发货的或者是已付款代发货的，才能申请退款 */
		elseif($order['status'] !=20 && $order['status'] !=30){ 
			$this->show_warning('只有已付款或者已发货的订单才能申请退款');
			exit;

		}
		elseif($order['payment_code'] != 'deposit') {
			$this->show_warning('该订单没有通过预存款支付，不能申请退款');
			exit;
		}

	}
	
	function receive()
	{
		$_GET['status'] == 'on' && $condition = " AND status NOT IN ('SUCCESS','CLOSED')";
		$page    =   $this->_get_page(10);   //获取分页信息
		$refunds = $this->_refund_mod->find(array(
			'conditions'	=> 'seller_id='.$this->visitor->get('user_id').$condition,
			'order' 		=> 'created desc',
			'limit'			=> $page['limit'],
			'count'   		=> true
		));
		$page['item_count']=$this->_refund_mod->getCount();
		foreach($refunds as $key=>$refund)
		{
			$member = $this->_member_mod->get(array('conditions'=>'user_id='.$refund['buyer_id'],'fields'=>'user_name'));
			$refunds[$key]['user_name'] = $member['user_name'];
						
			$ordergoods = $this->_ordergoods_mod->find(array('conditions'=>'order_id='.$refund['order_id'],'fields'=>'goods_name'));
			if(count($ordergoods) > 1){
				$ext = Lang::get('and_more');
			} else $ext = '';
			$goods = current($ordergoods);
			
			$refunds[$key]['goods_name'] = $goods['goods_name'] . $ext;
			
			$order = $this->_order_mod->get(array('conditions'=>'order_id='.$refund['order_id'],'fields'=>'order_sn'));
			$refunds[$key]['order_sn'] = $order['order_sn'];
			
			$refunds[$key]['refund_fee'] = $refund['refund_goods_fee'] + $refund['refund_shipping_fee'];
		}
		$this->_format_page($page);
		$this->assign('page_info', $page); 
				
		$this->_get_curlocal_title('refund_receive');
        $this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('refund_receive'));
		$this->assign('refunds',$refunds);
		$this->display('refund.receive.html');		
	}
	

	function _check_post_data($order_id, $post)
	{
		$order = $this->_order_mod->get($order_id);

		$shipping_info = $this->_order_extm_mod->get($order_id);
		

		if(empty($post['refund_goods_fee']) || floatval($post['refund_goods_fee'])<0)
		{
			$this->show_warning('refund_fee_ge0');
			exit;
			

		} elseif(floatval($post['refund_goods_fee']) > $order['goods_amount']){

			$this->show_warning('refund_fee_error');
			exit;
		}
		if($post['refund_shipping_fee'] !='' && floatval($post['refund_shipping_fee'])<0)
		{
			$this->show_warning('refund_shipping_fee_ge0');
			exit;
			
		}

		if(floatval($post['refund_shipping_fee']) > $shipping_info['shipping_fee']){

			$this->show_warning('refund_shipping_fee_error');
			exit;
		}
		if(!in_array(trim($post['shipped']), array(0,1,2))) {
			$this->show_warning('select_refund_shipped');
			exit;
		}
		if(empty($post['refund_reason'])){
			$this->show_warning('select_refund_reason');
			exit;
		}
	}
	
	
	
	/**
     * 上传凭证
     *
     */
    function _upload_files()
    {
        import('uploader.lib');
        $data      = array();
        $file = $_FILES['refund_cert'];
        if ($file['error'] == UPLOAD_ERR_OK && $file !='')
        {
            $uploader = new Uploader();
            $uploader->allowed_type(IMAGE_FILE_TYPE);
            $uploader->addFile($file);
            $uploader->root_dir(ROOT_PATH);
            $data['refund_cert'] = $uploader->save('data/files/refund_cert/member_'.$this->visitor->get('user_id'), $uploader->random_filename());
        }
        return $data;
    }

}

?>
